package exception;

// 1. 自定义受检异常（继承Exception）
class InsufficientFundsException extends Exception {
    private double currentBalance;
    private double amount;

    // 构造方法
    public InsufficientFundsException(double currentBalance, double amount) {
        super("余额不足: 当前余额 " + currentBalance + ", 需要 " + amount);
        this.currentBalance = currentBalance;
        this.amount = amount;
    }

    // 自定义方法
    public double getDeficit() {
        return amount - currentBalance;
    }
}

// 2. 自定义非受检异常（继承RuntimeException）
class InvalidAccountException extends RuntimeException {
    public InvalidAccountException(String accountNumber) {
        super("无效的账号: " + accountNumber);
    }
}

// 3. 使用自定义异常
class BankAccount {
    private String accountNumber;
    private double balance;

    public BankAccount(String accountNumber, double initialBalance) {
        if (accountNumber == null || accountNumber.trim().isEmpty()) {
            // 抛出自定义非受检异常
            throw new InvalidAccountException(accountNumber);
        }
        this.accountNumber = accountNumber;
        this.balance = initialBalance;
    }

    public void withdraw(double amount) throws InsufficientFundsException {
        if (amount <= 0) {
            throw new IllegalArgumentException("取款金额必须为正数");
        }

        if (amount > balance) {
            // 抛出自定义受检异常
            throw new InsufficientFundsException(balance, amount);
        }

        balance -= amount;
        System.out.println("取款成功: " + amount + ", 剩余余额: " + balance);
    }

    public String getAccountNumber() {
        return accountNumber;
    }
}

// 测试自定义异常
public class CustomExceptionDemo {
    public static void main(String[] args) {
        // 测试InvalidAccountException
        try {
            BankAccount invalidAccount = new BankAccount("", 1000);
        } catch (InvalidAccountException e) {
            System.out.println("错误: " + e.getMessage());
        }

        // 测试InsufficientFundsException
        try {
            BankAccount account = new BankAccount("123456", 1000);
            System.out.println("账号: " + account.getAccountNumber());
            account.withdraw(1500); // 取款金额大于余额
        } catch (InsufficientFundsException e) {
            System.out.println("错误: " + e.getMessage());
            System.out.println("差额: " + e.getDeficit());
        } catch (IllegalArgumentException e) {
            System.out.println("参数错误: " + e.getMessage());
        }
    }
}
